package com.ruoyi.framework.utils;

import com.ruoyi.common.core.resource.OperatorUserSystem;
import com.ruoyi.common.exception.CustomException;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * Global session manage
 * @author Xiaoming
 */
public class SessionHelper {

    /**
     *
     * Get current thread httpServletRequest
     */
    @NonNull
    public static HttpServletRequest getContextRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        Assert.notNull(requestAttributes,"Get current thread requestAttributes example fail");

        return ((ServletRequestAttributes)requestAttributes).getRequest();
    }

    /**
     *
     * Get current thread httpServletRequest
     */
    @NonNull
    public static HttpServletResponse getContextResponse(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        Assert.notNull(requestAttributes,"Get current thread requestAttributes example fail");

        return ((ServletRequestAttributes)requestAttributes).getResponse();
    }

    /**
     * Get current thread request session id
     */
    @NonNull
    public static String getContextRequestId(){
        HttpServletRequest request = getContextRequest();
        return request.getSession().getId();
    }


    /**
     * Get current thread request header value by headerKey.
     */
    public static Optional<String> getRequestHeader(@NonNull String headerKey){
        HttpServletRequest request = getContextRequest();
        return Optional.ofNullable(request.getHeader(headerKey));
    }

    public static boolean isClientRequest(){
        Optional<String> clientType = getClientRequest();
        return clientType.get().equals(OperatorUserSystem.CLIENT_USER.name());
    }

    public static boolean isPluginRequest(){
        Optional<String> clientType = getClientRequest();
        return clientType.get().equals(OperatorUserSystem.PLUGIN.name());
    }

    public static Optional<String> getClientRequest(){
        Optional<String> clientType = getRequestHeader(com.ruoyi.common.constant.Constants.OPERATOR_USER_SYSTEM_HEADER);
        if(!clientType.isPresent()){
            throw new CustomException("异常请求");
        }
        return clientType;
    }

}
